******************************************************************************
	*** Table 5 ***
******************************************************************************
	
	//Use main data
	use "${maindta}", clear

//Generate median-distance scores
	qreg firm_score_est i.a1 [pw=wt_rs]
	predict score_minusmedian, resid
	
//Centered results 
	!del "${outtables}\RIF_recentered*"
	foreach var in CPIscore2017 polconiii vae_rs pve_rs gee_rs rqe_rs rle_rs cce_rs pwrshift_last5yrs {
		if "`var'"=="pwrshift_last5yrs" {
			local t i
		}
		if "`var'"!="pwrshift_last5yrs" {
			local t c
		}
		foreach q in 10 25 75 90  {
			rifhdreg score_minusmedian `t'.`var' [pw=wt_rs], rif(q(`q'))  cluster(strata_all)
			outreg2 using "${outtables}\RIF_recentered_`var'" , append ctitle("`q'th") keep(`t'.`var') label dta dec(3)
		}
	}
	
//Take the output above and compile it 

	*Program for dropping columns when all rows are missing
		cap program drop colsallmiss
		program define colsallmiss 
		version 12.0
		syntax varlist , [DROPVARS GEN(string)] 

			ds3 `varlist'
			local cols: word count `r(varlist)'
			egen ___colsallmiss=rowmiss(`r(varlist)')
			if "`dropvars'"=="dropvars" {
				drop if ___colsallmiss==`cols'
			}
			if "`dropvars'"!="dropvars" {
				confirm new var `gen' //must specify new var
				if "`gen'"==""{
					di as error "Must specify a variable for obs with all specified rows missing"
				}
				gen `gen'=(___colsallmiss==`cols')
			}
			drop ___colsallmiss
		end 
		
	*Use and append datasets
		use "${outtables}\RIF_recentered_CPIscore2017_dta.dta" , clear
		colsallmiss **, dropvars 
		
	*Do this part for just the first iteration
		drop in 1
		levelsof v2 if v1=="Observations" , loc(obs) clean
		replace v1=v1 + " (n=`obs')" in 2
		drop if v1=="R-squared" | v1=="Robust standard errors in parentheses" | regexm(v1, "p<") | v1=="Observations"
		keep in 1/3
		preserve

	*Loop and append
		local ct=1
		foreach var in polconiii vae_rs pve_rs gee_rs rqe_rs rle_rs cce_rs pwrshift_last5yrs {
			use "${outtables}\RIF_recentered_`var'_dta.dta" , clear
			colsallmiss **, dropvars 
			drop in 1/2
			levelsof v2 if v1=="Observations" , loc(obs) clean
			replace v1=v1 + " (n=`obs')" in 1
			drop if v1=="R-squared" | v1=="Robust standard errors in parentheses" | regexm(v1, "p<") | v1=="Observations"
			keep in 1/3
			tempfile _`ct'
			save `_`ct''
			local ct=`ct'+1
		}
		local ct=`ct'-1
		
		restore
			
		forval f=1/`ct' {
			append using `_`f''
		}
		
		replace v1="GOVERNANCE" if v1=="VARIABLES"
		replace v1="Voice \& Accountability" if regexm(v1, "Voice &")
		
		drop if v1=="Constant"
		
		gen table5=v1+"&"+v2+"&"+v3+"&"+v4+"&"+v5+"\\"
		
	export delimited table5 using "${outtables}\\Table5.txt", nolabel noquote replace
